package org.zfes.snowy.ss.config.configrations;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerRequestExecutor;
import org.zfes.snowy.httpinvoke.SnowyAuthHttpComponentsHttpInvokerRequestExecutor;

@Configuration
public class HttpInvokeConfigration {
	//@Lazy(true)
	@Bean
	@ConditionalOnMissingBean
	public HttpInvokerRequestExecutor customHttpInvoker() {
		HttpInvokerRequestExecutor invoker = new SnowyAuthHttpComponentsHttpInvokerRequestExecutor(httpClient());
		//HttpInvokerRequestExecutor invoker = new HttpComponentsHttpInvokerRequestExecutor(httpClient());
		return invoker;
	}
	
	
	/**
	 * {@link org.apache.http.client.HttpClient}.-->getConnectionManager  api 过期< br>
	 * 所以 ：使用 {@link org.apache.http.impl.client.HttpClientBuilder}
	 * 
	 * @return
	 */
	private HttpClient httpClient() {
		CloseableHttpClient httpclient = HttpClients.custom()
				.setDefaultRequestConfig(requestConfig())
				.setConnectionManager(connectionManager())
				.setRedirectStrategy(new LaxRedirectStrategy())
				.build();
		return httpclient;
	}
	
	private RequestConfig requestConfig() {
		int oneMinute = 60 * 1000;
		return RequestConfig.custom()
				.setConnectTimeout(oneMinute)
				.build();
	}
	
	private HttpClientConnectionManager connectionManager() {
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
		connectionManager.setMaxTotal(100);
		connectionManager.setDefaultMaxPerRoute(5);
		return connectionManager;
	}

	
}
